﻿
var currentUserAccount = $().SPServices.SPGetCurrentUser({
    fieldName: "Name",
    debug: false
});
var thisUserName = $().SPServices.SPGetCurrentUser({
    fieldName: "Title",
    debug: false
});

var siteName = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');

var appWebUrl = siteName;
var targetSiteUrl = siteName;
var digest = "";
var ready = false;


currentUserAccount = currentUserAccount.split('\\')[1]

function AddDeleteLike(id) {
    var isCurrentUserLike = $('#like-' + id).text();
    // alert(isCurrentUserLike);


    $.ajax({

        url: "/_vti_bin/Portal/Service.svc/AddDeleteLike/userlogin=" + currentUserAccount + "/id=" + id + "/isCurrentUserLike=" + isCurrentUserLike,
        type: 'POST',
        success: function (data, textStatus, xhr) {
            //alert(id);
            if ($('#like-' + data).text() == 'Like') {
                $('#like-' + data).text('Unlike');
                var beforeLikers = $('span.like-' + data).attr('PortalTitle');
                var afterLikers = beforeLikers + thisUserName + "<br/>";
                $('span.like-' + data).attr('title', afterLikers);
                $('span.like-' + data).attr('PortalTitle', afterLikers);
                $('.like-' + data).tipTip({ defaultPosition: "top" });
                var earlierLikes = $('.like-' + data).text().split(' ');
                var newLikes = parseInt(earlierLikes) + 1;
                $('.like-' + data).text(newLikes + " People Like this");
            }
            else {
                $('#like-' + data).text('Like');
                var beforeLikers = $('span.like-' + data).attr('PortalTitle');
                var afterLikers = beforeLikers.replace(thisUserName + "<br/>", "");
                $('span.like-' + data).attr('title', afterLikers);
                $('span.like-' + data).attr('PortalTitle', afterLikers);
                var earlierLikes = parseInt($('.like-' + data).text().split(' '));
                if (earlierLikes > 0) {
                    var newLikes = earlierLikes - 1;
                    $('.like-' + data).text(newLikes + " People Like this");
                }
                $('.like-' + data).tipTip({ defaultPosition: "top" });
            }
        },
        error: function (msg) {
            //  alert(msg);
        }
    });
}


function ads(e, id, commentbody) {
    if (e.keyCode == 13) {

        $("form").submit(function () { return false; });

        AddComment(id, commentbody);
    }
    return false;

}


function AddComment(id, commentbody) {

    if (commentbody == "") {
        return;
    }

    var Orcommentbody = (commentbody);
    //commentbody = encodeURIComponent("/_vti_bin/Portal/Service.svc/AddComment/id=" + id + "/user=" + currentUserAccount+"/commentbody="+commentbody);
    commentbody = escape(commentbody);


    $.ajax({

        url: "/_vti_bin/Portal/Service.svc/AddComment/?id=" + id + "&user=" + currentUserAccount + "&commentbody=" + commentbody,
        type: 'POST',
        success: function (data, textStatus, xhr) {
            //alert(commentbody + id)
            var commentitem = "<div class='commentitem'>";
            commentitem += "<div class='commentor'>" + thisUserName + "</div>";
            commentitem += "<div class='commentbody'>" + Orcommentbody + "</div>";
            commentitem += "</div>";

            $('#comment-' + id).prepend(commentitem);

            var countearlier = parseInt($('.comcount-' + id).text());

            var newcount = countearlier + 1;
            $('.comcount-' + id).text(newcount);

            $('#feed-' + id + ' input').val("");
        }
    });


}

function GetAllLikes(id) {
    $.ajax({

        url: "/_vti_bin/Portal/Service.svc/GetAllLikes/?id=" + id,
        type: 'POST',
        success: function (data, textStatus, xhr) {
            try {
                var isCurrentLike = data.IsCurrentUserLike;
                var idItem = data.iditem;

                if (isCurrentLike) {

                    $("#like-" + idItem).text("Unlike");
                }
                else {

                    $("#like-" + idItem).text("Like");
                }
                var peopleLikers = "";
                for (var i = 0; i < data.UserLikes.length; i++) {
                    var name = data.UserLikes[i];

                    peopleLikers += name + "<br/>";
                }

                $('.like-' + idItem).attr('title', peopleLikers);
                $('.like-' + idItem).attr('PortalTitle', peopleLikers);
                $('.like-' + idItem).text(data.NumberOfLikes + " People Like this");
                $('.like-' + idItem).tipTip({ defaultPosition: "top" });

            }
            catch (ex) {
                console.log("GetAllLikes" + ex);
            }


        }

    });
}

function GetAllComments(id) {
    var idofItem = id;
    $.ajax({
        url: "/_vti_bin/Portal/Service.svc/AllComments/?id=" + id,
        type: "GET",
        success: function (data, textStatus, xhr) {

            for (var i = 0; i < data.length; i++) {
                var commentBody = data[i].CommentBody;
                var commentDate = data[i].CommentDate;
                var commentor = data[i].Commentor;
                var itemid = data[i].itemID;
                var commentitem = "<div class='commentitem'>";
                commentitem += "<div class='commentor'>" + commentor + "</div>";
                commentitem += "<div class='commentbody'>" + commentBody + "</div>";
                commentitem += "</div>";

                $('#comment-' + itemid.split('#')[1]).append(commentitem);


            }
            if (data.length > 0) {
                $('#feed-' + itemid.split('#')[1] + ' .commentsTitle').html("<span class='comcount-" + itemid.split('#')[1] + "'>" + data.length + "</span> Comments");
            }
            else {
                $('#feed-' + idofItem + ' .commentsTitle').html("<span class='comcount-" + idofItem + "'>0</span> Comments");
            }

        }
    });
}

function UploadFile() {
    // if we have not finished loading scripts then display an alert
    if (!ready) {
        alert("Oooooops... Please wait for the page to finish loading before attempting to upload a file");
        return;
    }

    // get the library name and file reference
    var docLibrary = "PortalDocuments";
    var fileInput = $('#fileSelectorInput');

    // if there is no document library name alert the user and return
    if (!docLibrary || docLibrary == '') {
        alert("Oooooops... It doesn't look like you entered the name of the library you would like to upload your file to");
        return;
    }

    // if we couldnt get a reference to the file input then alert the user and return
    if (!fileInput || fileInput.length != 1) {
        alert('Oooooops... An error occured processing your input.');
        return;
    }
    else if (!fileInput[0].files) {
        alert("Oooooops... It doesn't look like your browse supports uploading files in this way");
        return;
    }
    else if (fileInput[0].files.length <= 0) {
        alert("Oooooops it doesn't look like you selected a file. Please select a file and try again.");
        return;
    }

    // for each file in the list of files process the upload
    for (var i = 0; i < fileInput[0].files.length; i++) {
        var file = fileInput[0].files[i];
        ProcessUpload(file, docLibrary, '');
    }
}

function ProcessUpload(fileInput, docLibraryName, folderName) {
    var reader = new FileReader();
    reader.onload = function (result) {
        var fileName = '',
         libraryName = '',
         fileData = '';

        var byteArray = new Uint8Array(result.target.result)
        for (var i = 0; i < byteArray.byteLength; i++) {
            fileData += String.fromCharCode(byteArray[i])
        }

        // once we have the file perform the actual upload
        PerformUpload(docLibraryName, fileInput.name, folderName, fileData);

    };
    reader.readAsArrayBuffer(fileInput);
}

function PerformUpload(libraryName, fileName, folderName, fileData) {
    var url;

    // if there is no folder name then just upload to the root folder
    if (folderName == "") {
        url = appWebUrl + "/_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?" +
            "@TargetSite='" + targetSiteUrl + "'" +
            "&@TargetLibrary='" + libraryName + "'" +
            "&@TargetFileName='" + fileName + "'";
    }
    else {
        // if there is a folder name then upload into this folder
        url = appWebUrl + "/_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/folders(@TargetFolderName)/files/add(url=@TargetFileName,overwrite='true')?" +
           "@TargetSite='" + targetSiteUrl + "'" +
           "&@TargetLibrary='" + libraryName + "'" +
           "&@TargetFolderName='" + folderName + "'" +
           "&@TargetFileName='" + fileName + "'";
    }

    // use the request executor (cross domain library) to perform the upload
    var reqExecutor = new SP.RequestExecutor(appWebUrl);
    reqExecutor.executeAsync({
        url: url,
        method: "POST",
        //headers: {
        //    "Accept": "application/json; odata=verbose",
        //    "X-RequestDigest": digest
        //},
        contentType: "application/json;odata=verbose",
        binaryStringRequestBody: true,
        body: fileData,
        success: function (x, y, z) {
            alert("Success! Your file was uploaded to SharePoint.");
        },
        error: function (x, y, z) {
            alert("Oooooops... it looks like something went wrong uploading your file." + x + "   " + y + "   " + z);
        }
    });
}


function readytoUpload() {
    digest = $("#__REQUESTDIGEST").val();

    // load the request executor script, once ready set a flag that can be used to check against later
    $.getScript(appWebUrl + "/_layouts/15/SP.RequestExecutor.js", function () {
        ready = true;
    });
}

//function pageLoad(sender, args) {


//}

